package com.example.springsecurity.auth.qq.api;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.social.oauth2.AbstractOAuth2ApiBinding;
import org.springframework.social.oauth2.TokenStrategy;

/**
 * 定义qq接口实现类
 */
public class QQImpl extends AbstractOAuth2ApiBinding implements QQ {

    private Logger logger = LoggerFactory.getLogger(getClass());

    //用于获取openId的url
    private static final String URL_GET_OPENID = "https://graph.qq.com/oauth2.0/me?access_token=%s";

    //用于获取用户信息的url  其中access_token : 这个参数  父类会处理
    private static final String URL_GET_USERINFO = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s";

    private String appId;

    private String openId;

    //转换json对象
    private ObjectMapper objectMapper = new ObjectMapper();

    //编写构造方法处理参数
    public QQImpl(String accessToken, String appId) {
        /**
         * 调用父类方法  处理accessToken  把他拼接到url上
         * 父类一个参数的方法  默认把accessToken放到了请求头里  我们需要放到url参数里
         */
        super(accessToken, TokenStrategy.ACCESS_TOKEN_PARAMETER);

        this.appId = appId;

        //获取openId
        String url = String.format(URL_GET_OPENID,accessToken);//会把accessToken代替%s 拼接到url上
        String result = getRestTemplate().getForObject(url,String.class);//发送url请求  返回为strign类型

        logger.info("URL_GET_OPENID返回结果 : {}",result);
        //把openId截取出来
        this.openId = StringUtils.substringBetween(result,"\"openid\":","}");
        logger.info("openId : {}",openId);
    }

    //发送请求获取用户信息
    @Override
    public QQUserInfo getUserInfo() {
        //发送请求获取用户信息
        String url = String.format(URL_GET_USERINFO,appId,openId);
        String result = getRestTemplate().getForObject(url,String.class);
        logger.info("URL_GET_USERINFO获取用户数据 : {}",result);
        try {
            QQUserInfo qqUserInfo = objectMapper.readValue(result, QQUserInfo.class);
            qqUserInfo.setOpenId(openId);//***********
            return qqUserInfo;
        } catch (Exception e) {
            new RuntimeException("获取用户信息失败",e);
            return null;
        }
    }
}
